package top.kaoshanji.p1ch03a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch03a-62页a：一个完全持续的计数器
 * URL访问地址：/initDestroyCounter
 * @author kaoshanji
 * ^_^
 * create time 2025/4/3 13:51
 */
public class InitDestroyCounter extends HttpServlet {

    private static final String INIT_DESTROY_COUNTER = "InitDestroyCounter.initial";

    int count;

    @Override
    public void init() throws ServletException {

        // 从三个地方获取值，这不就是 Spring 获取 Bean 的过程了

        // 第一：尝试从存储的状态载入初始值
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;

        try {
            fileReader = new FileReader(INIT_DESTROY_COUNTER);
            bufferedReader = new BufferedReader(fileReader);
            String initial = bufferedReader.readLine();
            count = Integer.parseInt(initial);
            return;

        } catch (IOException e) {
            // throw new RuntimeException(e); // 抛出该异常下面的 try-catch 语句块之外语法错误了
            ///
        } finally {
            // 确定关闭文件
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
               ///
            }
        }

        // 第二：防止未存储状态，查看初始变量
        try {
            String initial = getInitParameter("initial");
            count = Integer.parseInt(initial);
            return;
        } catch (NumberFormatException e) {
            ///  空或非整数值
        }

        // 第三：使初始值默认为0
        count = 0;

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = resp.getWriter(); // 这是写入网络

        count++;

        out.println("Since the beginning, this servlet has been accessed " + count + " times.");

    }

    @Override
    public void destroy() {
        super.destroy(); // 可选
        saveState();
    }

    private void saveState() {
        // 保存数值
        FileWriter fileWriter = null;
        PrintWriter printWriter = null;
        try {
            fileWriter = new FileWriter(INIT_DESTROY_COUNTER);
            // 这是写入文件
            printWriter = new PrintWriter(fileWriter); // PrintWriter 只管写入，至于写到那里由创建它时指定，可以是文件，也可以是网络
            printWriter.println(count);
            return;
        } catch (Exception e) {
            ///  写中产生的问题
        } finally {
            // 确定关闭文件
            if (printWriter != null) {
                printWriter.close();
            }
        }

    }

}
